import {
  List
} from 'immutable';
import {
  createReducer
} from "./redux-action-tools"


import {
  ADD_TAB_PAGE,
  SELECT_TAB_PAGE,
  DELETE_TAB_PAGE
} from "../actions/const"

const reducer = createReducer()
  .when(ADD_TAB_PAGE, function (state, action) {
    const { title, url } = action;
    const index = state.get("list").findIndex(tab => tab.title == title);
    if (index == -1) {
      return state.withMutations(state => {
        state.update("list", list => list.push({ title, url, deletable: true}))
          .set("selectTitle", title);
      })
    }
    else {
      return state.set("selectTitle", title);
    }
  })
  .when(SELECT_TAB_PAGE, function (state, action) {
    const { title } = action;
    return state.set("selectTitle", title);
  })
  .when(DELETE_TAB_PAGE, function (state, action) {
    const { title } = action;
    const index = state.get("list").findIndex(tab => tab.title == title);
    if (index != -1) {
      return state.withMutations(state => {
        state.deleteIn(["list", index]).delete("selectTitle");
      })
    }
    else{
      return state.delete("selectTitle");
    }
  })
  .build(List());

export default reducer;